<template>
    <el-form label-width="80px" size="normal">
        <el-form-item label="SPU名称">
            <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
            <el-select placeholder="请选择" v-model="spuInfo.tmId"> 
                <el-option v-for="tk in tdmkList" :key="tk.id" :value="tk.id" :label="tk.tmName"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input placeholder="SPU描述" type="textarea" rows="4" v-model="spuInfo.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImageList"
                :action="`${baseUrl}/admin/product/upload`" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
            <el-select :placeholder="`还有${unUseSaleAttr.length}未选择`" v-model="tempAttr"> 
                <el-option v-for="allSale in unUseSaleAttr" :key="allSale.id" :value="`${allSale.id}:${allSale.name}`" :label="allSale.name"></el-option>
            </el-select>
            <el-button type="primary" size="default" @click="addSaleAttr" :disabled="!tempAttr">添加销售属性</el-button>
        </el-form-item>
        <el-form-item>
            <el-table  :data="nowSaleAttrList" border stripe>
                <el-table-column type="index" width="80" label="序号" />
                <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
                <el-table-column label="属性值名称列表">
                    <template #="{row}">
                        <el-tag
                        :key="tag"
                        v-for="(tag,index) in row.spuSaleAttrValueList"
                        closable
                        :disable-transitions="false"
                        @close="row.spuSaleAttrValueList.splice(index,1)"
                        >
                        {{tag.saleAttrValueName}}
                        </el-tag>
                        <el-input
                        class="input-new-tag"
                        size="small"
                        v-if="row.isEdit"
                        ref="inpEle"
                        @blur="changeToLook(row)"
                        v-model="row.inputValue"
                        >
                        </el-input>
                        <el-button class="button-new-tag" size="small" v-else @click="changeToEdit(row)">+ 添加属性值</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #="{row,$index}">
                        <el-button type="danger" size="default" @click="nowSaleAttrList.splice($index,1)" icon="ele-Delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="default" @click="save">确认</el-button>
            <el-button type="default" size="default" @click="emit('setState',0)">取消</el-button>
        </el-form-item>
    </el-form>

</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "SpuForm",
});
</script>

<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
import { requestNowSpuImageList, requestNowSpuSaleAttrList, requestAllBaseSaleAttrList,
    type reqSpuBaseSaleType, type reqSpuImageListType, type reqSpuInfoType, type reqSpuSaleAttrListType, type reqSpuSaleAttrListItemType, type reqSpuSaleAttrValueListItemType, requestUpdateSpu, requestAddSpu } from '@/api/spu';

import { requestAllTrademark, type reqTrademarkRecordsType } from '@/api/trademark';

const baseUrl = import.meta.env.VITE_API_URL;
//照片墙
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
//接收props传参
const props = defineProps<{
    spuInfo: reqSpuInfoType
}>()
//接收自定义事件
const emit = defineEmits<{
        (event:'setState',state:number,row?:reqSpuInfoType):void
}>()
//定义品牌列表，图片列表，销售属性列表，当前spu销售属性列表
const tdmkList = ref<reqTrademarkRecordsType>([])
const spuImageList = ref<reqSpuImageListType>([])
const allSaleAttrList = ref<reqSpuBaseSaleType>([])
const nowSaleAttrList = ref<reqSpuSaleAttrListType>([])

//初始化请求
const getAllUseData = async () => {
    if(!props.spuInfo.id){
        try {
            //获取品牌列表
            const re = await requestAllTrademark()
            tdmkList.value = re
            //获取销售属性列表
            const re1 = await requestAllBaseSaleAttrList()
            allSaleAttrList.value = re1
        } catch (e) {
            ElMessage.error('获取品牌或销售属性失败')
        }
    }else{
         //获取品牌列表
         const req1 = requestAllTrademark()
        //获取销售属性列表
        const req2 = requestAllBaseSaleAttrList()
        //获取图片列表
        const req3 = requestNowSpuImageList(props.spuInfo.id)
        //获取当前销售属性列表
        const req4 = requestNowSpuSaleAttrList(props.spuInfo.id)
        try {
            const result = await Promise.all([req1,req2,req3,req4])
            tdmkList.value = result[0]
            allSaleAttrList.value = result[1]
            spuImageList.value = result[2]
            //获取到图片列表，给每一项添加属性，显示图片
            spuImageList.value.forEach(item => {
                item.name = item.imgName
                item.url = item.imgUrl
            })
            nowSaleAttrList.value = result[3]
            //都添加属性，控制是否可编辑
            nowSaleAttrList.value.forEach(item => {
                item.isEdit = false,
                item.inputValue = '' //收集用户属性值
            })
        } catch (e) {
            ElMessage.error('初始化请求失败')
        }
    }
}
//初始化请求
onMounted(() => {
    getAllUseData()
})

//计算属性计算未选择列表
const unUseSaleAttr = computed(() => {
    return allSaleAttrList.value.filter(item1 => {
        return nowSaleAttrList.value.every(item2 => {
            return item2.saleAttrName !== item1.name
        })
    })
})

//保存用户输入信息
const tempAttr = ref('')

//点击添加销售属性
const addSaleAttr = () => {
    //创建一个销售属性
    const newSaleAttr = ref<reqSpuSaleAttrListItemType>({
        baseSaleAttrId: +tempAttr.value.split(':')[0],
        saleAttrName: tempAttr.value.split(':')[1],
        spuSaleAttrValueList: [],
        isEdit: false, //控制当前是否可编辑
        inputValue: '' //保存用户输入的属性值
    })
    //添加到数组中
    nowSaleAttrList.value.push(newSaleAttr.value)
    //清空用户输入信息
    tempAttr.value = ''
}

//获取输入框元素
const inpEle = ref()
//点击添加属性，变成可编辑模式
const changeToEdit = (row:reqSpuSaleAttrListItemType) => {
    row.isEdit = true
    //自动获取焦点
    nextTick(() => {
        inpEle.value.focus()
    })
}
//失去焦点变成查看模式
const changeToLook = (row:reqSpuSaleAttrListItemType) => {
    //判断用户输入是否为空
    if(!row.inputValue?.trim()){
        //变成查看模式
        return row.isEdit = false
    }
    //判断是否重复
    const isReset = row.spuSaleAttrValueList.some(item => {
       return item.saleAttrValueName === row.inputValue
    })
    
    if(isReset){
        //清空
        row.inputValue = ''
        //变成查看模式
        row.isEdit = false
        return;
    }
    //创建一个属性值
    const newSaleAttrValue = ref<reqSpuSaleAttrValueListItemType>({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue as string
    })
    //添加到数组
    row.spuSaleAttrValueList.push(newSaleAttrValue.value)
    //清空
    row.inputValue = ''
    //变成查看模式
    row.isEdit = false
}

//点击确认，发送请求
const save = async () => {
    //整理图片列表数据
    const newImageList = spuImageList.value.map(item => {
        if(item.response){
            return {
                imgName: item.name as string,
                imgUrl: item.response.data
            }
        }else{
            return {
                imgName: item.imgName,
                imgUrl: item.imgUrl
            }
        }
    })
    //整理销售属性列表
    nowSaleAttrList.value.map(item => {
        delete item.isEdit
        delete item.inputValue
    })
    //赋值给上传数据
    props.spuInfo.spuImageList = newImageList
    props.spuInfo.spuSaleAttrList = nowSaleAttrList.value
    //发送请求
    try {
        if(props.spuInfo.id){
            await requestUpdateSpu(props.spuInfo)
            ElMessage.success('修改成功')
        }else{
            await requestAddSpu(props.spuInfo)
            ElMessage.success('添加成功')
        }
    } catch (e) {
        ElMessage.error('修改或添加失败')
    }
    //回到列表页
    emit('setState',0)
}
</script>